package com.weijianhuawen.wjblog.jwt.helper;

import com.weijianhuawen.wjblog.common.exception.UserException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Component;

import javax.security.auth.login.CredentialException;
import javax.security.auth.login.CredentialExpiredException;
import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Base64;
import java.util.Date;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description: jwt密钥配置
 * @date: 2024-10-15 23:50
 */
@Component
public class JwtTokenHelper implements InitializingBean {
    //签发人
    @Value("${jwt.issuer}")
    private String issuer;

    //密钥
    private Key key;

    //jwt解析
    private JwtParser jwtParser;

    /**
     * 解码配置文件中的Base64编码为密钥
     * @param base64Key key
     */
    @Value("${jwt.secret}")
    public void setBase64Key(String base64Key) {
        key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(base64Key));
    }

    /**
     * 初始化 JwtParse
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //服务器间可能存在时钟偏移 需设置最大忍受时钟误差
        jwtParser = Jwts.parserBuilder().requireIssuer(issuer)
                .setSigningKey(key).setAllowedClockSkewSeconds(10)
                .build();
    }

    @Value("${jwt.tokenExpireTime}")
    private Long tokenExpireTime;

    /**
     * 生成Token并设置有效期
     * @param username
     * @return
     */
    public String generateToken(String username) {
        LocalDateTime now = LocalDateTime.now();
        //为Token设置有效期为
        LocalDateTime expireTime = now.plusMinutes(tokenExpireTime);

        return Jwts.builder()
                .setSubject(username)
                .setIssuer(issuer)
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(expireTime.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(key)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Jws<Claims> parseToken(String token) {
        try {
            return jwtParser.parseClaimsJws(token);
        } catch (SignatureException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException e) {
            throw new BadCredentialsException("token 不可用", e);
        } catch (ExpiredJwtException e) {
            throw new CredentialsExpiredException("token 已过期", e);
        }
    }

    /**
     * 验证token是否有效
     * @param token
     */
    public void validateToken(String token) {
        jwtParser.parseClaimsJws(token);
    }

    public String getUsernameByToken(String token) {
        try {
            Claims claims = jwtParser.parseClaimsJws(token).getBody();
            String username = claims.getSubject();
            return username;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成安全密钥
     * @return
     */
    private static String generateBase64Key() {
        //生成安全密钥
        Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);

        //将密钥进行Base64编码
        String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded());

        return base64Key;
    }

    public static void main(String[] args) {
        String key = generateBase64Key();
        System.out.println("key: " + key);
    }
}
